package com.dajiangtai.interceptor;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dajiangtai.entity.User;
import com.dajiangtai.util.GlobalConfig;

public class LoginInterceptor implements HandlerInterceptor {
	private final Logger log = Logger.getLogger(this.getClass().getName());
	
	//在配置文件中设置excludedUrls参数
	private List<String> excludedUrls;
	 
	public void setExcludedUrls(List<String> excludedUrls) {
	    this.excludedUrls = excludedUrls;
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		//不过滤设定的方法函数，在配置文件中设置excludedUrls
		String requestUri = request.getRequestURI();
		//log.info("\n\nDW preHandle:" + requestUri);
	    for (String url : excludedUrls) {
	      if (requestUri.contains(url)) {
	        return true;
	      }
	    }
	    HttpSession session = request.getSession(false);//判断session是否失效
	    String root = GlobalConfig.get("webRoot");

	    if(session==null || session.getAttribute("dw_uid") == null){ 
	    	String url = request.getRequestURL().toString();
	    	if(url.startsWith(root + "m/")){
	    		root = root + "m/";
	    		log.info("From Mobile:" + root);
	    	}
	    	response.sendRedirect(root + "loginAdapter.do");
			return false;
	    }
	    if(requestUri.endsWith("admin.do")){
	    	int type = (Integer)session.getAttribute("dw_type");
	    	//只有管理员可以访问admin后缀的请求
	    	if(type != 9){
	    		response.sendRedirect(GlobalConfig.get("wwwRoot") + "error.do?code=1");
	    		return false;
	    	}
	    }
	    
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
